# -*- coding: utf-8 -*-
"""
@Time ： 2024/1/18 13:16
@Auth ： 李天天
"""
import os
from logzero import logger

from solox.public.apm import AppPerformanceMonitor
from solox.public.common import Devices


class DHDevices(Devices):
    def getPidNew(self, deviceId, pkgName):
        """Get the pid corresponding to the Android package name"""
        try:
            sdkversion = self.getSdkVersion(deviceId)
            if sdkversion and int(sdkversion) < 26:
                result = os.popen(f"{self.adb} -s {deviceId} shell ps | {self.filterType()} {pkgName}").readlines()
                processList = ['{}:{}'.format(process.split()[1], process.split()[8]) for process in result]
                # processList = ['{}:{}:{}'.format(process.split()[0],process.split()[1], process.split()[8]) for process in result]
                processListdic = [{"USER": process.split()[0], "PID": process.split()[1], "pkgName": process.split()[8]}
                                  for process in result]
            else:
                result = os.popen(f"{self.adb} -s {deviceId} shell ps -ef | {self.filterType()} {pkgName}").readlines()
                processList = ['{}:{}'.format(process.split()[1], process.split()[7]) for process in result]
                # processList = ['{}:{}:{}'.format(process.split()[0],process.split()[1], process.split()[7]) for process in result]
                processListdic = [{"USER": process.split()[0], "PID": process.split()[1], "pkgName": process.split()[7]}
                                  for process in result]
            for i in range(len(processList)):
                if processList[i].count(':') == 2:
                    index = processList.index(processList[i])
                    processList.insert(0, processList.pop(index))
                    break
            if len(processList) == 0:
                logger.warning('{}: no pid found'.format(pkgName))
        except Exception as e:
            processList = []
            logger.exception(e)
        return processListdic


if __name__ == '__main__':
    dhd = DHDevices()
    res = dhd.getPidNew(deviceId="838ba68", pkgName="com.arcvideo.car.video")
    print(res)
